home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2101 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.5 KB

  1. Path: damage.usa1.net!news
  2. From: Kin Chan <firstian@usa1.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: const member functions
  5. Date: Mon, 15 Jan 1996 14:09:53 +0000
  6. Organization: USAinternet, Inc.
  7. Message-ID: <30FA6031.39B8@usa1.com>
  8. References: <4d8d8f$b30@oznet07.ozemail.com.au>
  9. NNTP-Posting-Host: wmn1-175.usa1.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (Macintosh; I; PPC)
  14.  
  15. Oliver Jones wrote:
  16. > Email reply's please.
  17. > Could someone please explain to me the significance of the "const" in
  18. > this member function declaration.
  19. > int MyFunc(const char *s) const {
  20. >         ...
  21. > };
  22. > I became aware of these when my compiler complained I couldn't call a
  23. > non-const member function from a pointer to a const parameter class.
  24. > eg: I couldn't do this:
  25. > int MyFunc2(const TMyClass *p) {
  26. >         int i = p->MyFunc("hi");
  27. > }
  28. > I needed to add the const to the declaration above.  Care to explain
  29. > the significance and "side effects" of the const member as defined
  30. > above.
  31. > Thanks.
  32.  
  33. The meaning of the trailing const in the function declaration is a 
  34. promise to the compiler that the member function MyFunc() will not 
  35. modify the state of *this. In MyFunc2(), *p is a pointer to a const 
  36. TMyClass object (NOT a const pointer to a TMyClass object). 
  37. Therefore, in the scope of MyFunc2(), *p will be const, and you can 
  38. only call those member functions that promise not to alter its 
  39. state, i.e., the const member functions.
  40.